package com.gz.logistics.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.logistics.R;
import com.gz.logistics.adapter.OutingAssembleAdapter;
import com.gz.logistics.adapter.SpinnerAdapter;
import com.gz.logistics.app.Define;
import com.gz.logistics.app.OutingAssembleDetailActivity;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.GetPartsListener;
import com.gz.logistics.library.listener.GetWillOutOfStorageAssemblesListener;
import com.gz.logistics.library.listener.RequestCode;
import com.gz.logistics.library.listener.SignAllOrdersOfTheAssembleListener;
import com.gz.logistics.library.pojo.CustomerSpinnerObject;
import com.gz.logistics.library.pojo.PartInfo;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.pojo.WillOutStorageAassemble;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.CrashHandler;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.util.ToastUtils;
import com.gz.logistics.widget.DoubleDatePickerDialog;
import com.gz.logistics.widget.FooterView;
import com.gz.logistics.widget.LoadingCover;
import com.gz.logistics.widget.SpinerPopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


public class OutingFragment extends Fragment
        implements FooterView.OnFooterViewRefreshListener ,
        PullToRefreshBase.OnRefreshListener, LoadingCover.OnLoadingCoverRefreshListener,
        SpinerPopWindow.ISpinnerOnItemSelectListener, AdapterView.OnItemClickListener, View.OnClickListener,
        DoubleDatePickerDialog.OnDateSetListener, OutingAssembleAdapter.SignALLCallbackInterface {
    private String TAG = OutingFragment.class.getSimpleName();
    private View mConvertView;
    private UserInfo userInfo;
    private List<WillOutStorageAassemble> mDataList;

    private TextView iv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private RelativeLayout rl_choice_for_part;
    private RelativeLayout rl_choice_for_time;
    private RelativeLayout rl_choice_for_order;
    private TextView tv_part_name;
    private TextView tv_time;
    private TextView tv_order;
    private PullToRefreshListView mPullList;

    private LoadingCover mLoadingCover;
    private Context mContext;
    private Dialog mLoadingData;
    private FooterView mFooterView;
    private DoubleDatePickerDialog timeDialog;
    private Calendar mCalendar;

    private List<CustomerSpinnerObject> partList ;
    private SpinnerAdapter partSpinnerAdapter;
    private SpinerPopWindow mPartSpinnerPopWindow;


    private OutingAssembleAdapter assembleAdapter;
    private MyGetWillOutOfStorageAssemblesListener pullRequestListener;
    private MyGetWillOutOfStorageAssemblesListener scrollRequestListener;
    private MyGetPartsListener myGetPartsListener;
    private MySignAllOrdersOfTheAssembleListener  mySignAllOrdersOfTheAssembleListener;

    private MyHandler mHandler;

    private int page = 1;
    private int selectedPartId = -1;
    private String startTime = null;
    private String endTime = null;
    private int orderType = -1;



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mConvertView == null){
            mConvertView = inflater.inflate(R.layout.fragment_outing, container, false);
            init(inflater);
        }


        mDataList = new ArrayList<WillOutStorageAassemble>();
        assembleAdapter = new OutingAssembleAdapter(mDataList,mContext,this);
        mPullList.setAdapter(assembleAdapter);

        // 初始化"片区选择" 控件
        partList = new ArrayList<CustomerSpinnerObject>();
        partSpinnerAdapter = new SpinnerAdapter(this.getActivity(),partList);
        mPartSpinnerPopWindow = new SpinerPopWindow(this.getActivity());
        mPartSpinnerPopWindow.setAdatper(partSpinnerAdapter);
        mPartSpinnerPopWindow.setItemListener(this);

        mHandler = new MyHandler(this);

        initListener();
        onLoadingCoverRefresh();
        return mConvertView;


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        pullRequestListener.release();
        scrollRequestListener.release();
        mHandler.release();
        myGetPartsListener.release();
        mySignAllOrdersOfTheAssembleListener.release();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }



    /**
     * 点击加载更多回调时间
     */
    @Override
    public void onFooterViewRefresh() {
        page++;
        IOrder.getInstance().getWillOutStorageAssembles(selectedPartId, startTime, endTime, orderType, page, scrollRequestListener);

    }

    /**
     * 下拉刷新回调事件
     * @param refreshView
     */
    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        page = 1;
        startTime = null;
        endTime = null;
        selectedPartId = -1;
        IOrder.getInstance().getWillOutStorageAssembles(selectedPartId, startTime, endTime, orderType, page, pullRequestListener);
    }

    /**
     * LoadingCover 点击回调事件
     */
    @Override
    public void onLoadingCoverRefresh() {
        page = 1;
        startTime = null;
        endTime = null;
        selectedPartId = -1;
        IOrder.getInstance().getWillOutStorageAssembles(selectedPartId, startTime, endTime, orderType, page, pullRequestListener);
    }

    /**
     * 片区spinner 条目点击回调事件
     * @param position
     */
    @Override
    public void onSpinnerItemClick(int position) {
        if (position < 0){
            return;
        }
        for (int i = 0 ; i < partList.size() ; i ++){
            PartInfo info = (PartInfo) partList.get(i);
            if (info.getPart_id() == position){
                info.setIsSelected(true);
            }else{
                info.setIsSelected(false);
            }

        }
        //mPartSpinnerPopWindow.notifyDataSetChanged();
        mLoadingData.show();
        selectedPartId = ((PartInfo)partList.get(position)).getPart_id();
        page = 1;
        startTime = null;
        endTime = null;
        IOrder.getInstance().getWillOutStorageAssembles(selectedPartId, startTime, endTime, orderType, page, pullRequestListener);



    }

    /**
     * listview 条目点击回调事件
     * @param adapterView
     * @param view
     * @param i
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        CrashHandler.i(TAG,"onItemClick");
        if (l < 0){
            return ;
        }
        WillOutStorageAassemble clickItem = mDataList.get((int)l);
        if (clickItem != null){
            Intent intent = new Intent();
            intent.setClass(mContext, OutingAssembleDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("storage_out_id", clickItem.getPre_storage_out());
            intent.putExtras(bundle);
            startActivityForResult(intent, Define.ACTIVITY_CODE_ORDER_DETAIL);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( requestCode == Define.ACTIVITY_CODE_ASSEMBLE_DETAIL && resultCode == Define.ACTIVITY_CODE_ASSEMBLE_DETAI_CHANGE){
            if (data != null){ // 如果预出库单详情页面 ，有订单状态发生改变，则刷新界面
                page = 1;
                startTime = null;
                endTime = null;
                selectedPartId = -1;
                IOrder.getInstance().getWillOutStorageAssembles(selectedPartId, startTime, endTime, orderType, page, pullRequestListener);
            }

        }
    }

    /**
     * 片区选择  时间选择 排序 按钮点击回调事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_choice_for_part:
                if(partList.size() <= 0 ){
                    ToastUtils.showToast(getActivity(),"片区列表为空");
                    return ;
                }
                mPartSpinnerPopWindow.setWidth(rl_choice_for_part.getWidth()*2);
                mPartSpinnerPopWindow.showAsDropDown(rl_choice_for_part);
                break;
            case R.id.rl_choice_for_time:
                timeDialog.show();
                break;
        }

    }



    /**
     *  弹出时间选择 Dialog，并选择对应开始和介素时间后，点击确定按钮，将会触发以下方法
     *
     */
    @Override
    public void onDateSet(DatePicker startDatePicker, int startYear,
                          int startMonthOfYear, int startDayOfMonth, DatePicker endDatePicker, int endYear,
                          int endMonthOfYear, int endDayOfMonth) {
        startTime = String.format("%d-%d-%d",startYear,startMonthOfYear+1,startDayOfMonth);
        endTime = String.format("%d-%d-%d",endYear,endMonthOfYear+1,endDayOfMonth);
        CrashHandler.i(TAG,"开始时间="+startTime+"结束时间=" +endTime);
        page = 1;
        selectedPartId = -1;
        mLoadingData.show();
        IOrder.getInstance().getWillOutStorageAssembles(selectedPartId, startTime, endTime, orderType, page, pullRequestListener);


    }

    /**
     * 点击签收其下所有订单，触发该方法
     * @param pre_out_number
     */
    @Override
    public void signAll(int pre_out_number) {
        mLoadingData.show();
        IOrder.getInstance().signAllOrdersOfThisAssemble(pre_out_number, mySignAllOrdersOfTheAssembleListener);

    }

    private void init(LayoutInflater mInflater) {

        mContext = getActivity().getApplicationContext();
        userInfo = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));

        mPullList = (PullToRefreshListView) mConvertView.findViewById(R.id.list);
        iv_actionbar_title = (TextView) mConvertView.findViewById(R.id.iv_actionbar_title);
        iv_actionbar_title.setText("预出库单查询");
        tv_actionbar_deliveryName = (TextView) mConvertView.findViewById(R.id.tv_actionbar_deliveryName);
        tv_actionbar_deliveryName.setText("配送员："+userInfo.getUser_name());

        rl_choice_for_part = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_part);
        rl_choice_for_time = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_time);
        rl_choice_for_order = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_order);

        tv_part_name = (TextView) mConvertView.findViewById(R.id.tv_part_name);
        tv_time = (TextView) mConvertView.findViewById(R.id.tv_time);
        tv_order = (TextView) mConvertView.findViewById(R.id.tv_order);
        mLoadingCover = (com.gz.logistics.widget.LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);

        mLoadingData = new Dialog(getActivity(),R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);

        mFooterView = (FooterView) mInflater.inflate(R.layout.footer_view, null);
        mPullList.getRefreshableView().addFooterView(mFooterView);
        mPullList.setOnScrollListener(mFooterView);

        mCalendar = Calendar.getInstance();
        timeDialog = new DoubleDatePickerDialog(this.getActivity(),0,this,
                mCalendar.get(Calendar.YEAR),mCalendar.get(Calendar.MONTH),mCalendar.get(Calendar.DATE),true);


    }

    private void initListener() {

        mPullList.setOnRefreshListener(this);
        mPullList.setOnItemClickListener(this);

        mFooterView.setOnFooterViewRefreshListener(this);
        mLoadingCover.setOnLoadingCoverRefreshListener(this);
        pullRequestListener = new MyGetWillOutOfStorageAssemblesListener(this,RequestCode.PULL);
        scrollRequestListener = new MyGetWillOutOfStorageAssemblesListener(this,RequestCode.SCROLL);
        myGetPartsListener = new MyGetPartsListener(this);
        mySignAllOrdersOfTheAssembleListener = new MySignAllOrdersOfTheAssembleListener(this);

        rl_choice_for_part.setOnClickListener(this);
        rl_choice_for_time.setOnClickListener(this);
        rl_choice_for_order.setOnClickListener(this);

    }

    /**
     * 预出库单列表 数据获取回调接口
     */
    private static class MyGetWillOutOfStorageAssemblesListener extends GetWillOutOfStorageAssemblesListener {
        private OutingFragment mOuter;

        public MyGetWillOutOfStorageAssemblesListener(OutingFragment mOuter,RequestCode code) {

            super(code);
            this.mOuter = mOuter;


        }
        public void release(){
            new WeakReference<OutingFragment>(mOuter);
        }

        @Override
        public void onNoConditionAssembles() {
            mOuter.mLoadingCover.onRefreshSuccess();
            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPullList.setOnScrollListener(null);
            if (mOuter.mPullList.isRefreshing()){
                mOuter.mPullList.getLoadingLayoutProxy().refreshSuccess();
            }if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }
            mOuter.mDataList.clear();
            mOuter.assembleAdapter.notifyDataSetChanged();
            ToastUtils.showToast(mOuter.getActivity(),"暂无内容");

        }

        @Override
        public void onResponseSuccess(List<WillOutStorageAassemble> assembles) {
            if (getRequestCode() == RequestCode.PULL){
                mOuter.mDataList.clear();
                mOuter.assembleAdapter.notifyDataSetChanged();
            }
            mOuter.mDataList.addAll(assembles);
            mOuter.assembleAdapter.notifyDataSetChanged();

            if (assembles.size() < Define.LISTVIEW_ITEM_MIN_SIZE){
                mOuter.mFooterView.onRefreshComplete();
                mOuter.mPullList.setOnScrollListener(null);
            }else{
                mOuter.mFooterView.onRefreshSuccess();
                mOuter.mPullList.setOnScrollListener(mOuter.mFooterView);
            }

            mOuter.mLoadingCover.onRefreshSuccess();
            if ( mOuter.mPullList.isRefreshing()) {
                mOuter.mPullList.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }

            // 通知主线程开一个子线程去从服务器获取片区列表
            mOuter.mHandler.sendEmptyMessage(1);
        }


        @Override
        public void onNoNetWork() {
            if (mOuter.mPullList.isRefreshing()){
                mOuter.mPullList.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.mFooterView.onRefreshFailed();
            mOuter.mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
            ToastUtils.showToast(mOuter.getActivity(), Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingCover.onRefreshFailed();
            mOuter.mFooterView.onRefreshFailed();
            if (mOuter.mPullList.isRefreshing()){
                mOuter.mPullList.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(),"请求失败");

        }
    }


    /**
     * 获取片区的监听器
     */
    public static  class MyGetPartsListener extends GetPartsListener{
        private OutingFragment mOuter;

        public MyGetPartsListener(OutingFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<OutingFragment>(mOuter);
        }

        @Override
        public void onResponseSuccess(List<PartInfo> partInfos) {
            PartInfo ignorePart = new PartInfo();
            ignorePart.setPart_id(-1);
            ignorePart.setIsSelected(false);
            ignorePart.setPart_name("全部片区");
            partInfos.add(0, ignorePart);

            mOuter.partList.clear();
            mOuter.partList.addAll(partInfos);
            mOuter.mHandler.sendEmptyMessage(2);


        }
        @Override
        public void onPartIsEmpty() {

        }
        @Override
        public void onResponseFailed() {

        }
    }



    /**
     * 签收其下所有订单 监听器
     */
    private static  class  MySignAllOrdersOfTheAssembleListener extends SignAllOrdersOfTheAssembleListener {
        private OutingFragment mOuter;

        public MySignAllOrdersOfTheAssembleListener(OutingFragment mOuter) {
            this.mOuter = mOuter;
        }
        public void release(){
            new WeakReference<OutingFragment>(mOuter);
        }

        @Override
        public void onPartOrdersSignFail() {
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(), "该预出库仍存在部分订单未签收成功");
            mOuter.onLoadingCoverRefresh();

        }

        @Override
        public void onNoSignableOrderInThisAssemble() {
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(), "该预出库下没有当前物流员可签收的订单");
            //mOuter.onLoadingCoverRefresh();
        }

        @Override
        public void onThisAssembleIsDiscarder() {
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(), "该预出库单已作废");
            //mOuter.onLoadingCoverRefresh();

        }

        @Override
        public void onResponseSuccess() {
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(), "签收成功");
            mOuter.onLoadingCoverRefresh();

        }

        @Override
        public void onNoNetWork() {
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(), Define.MSG_NO_NETWORK);
        }

        @Override
        public void onResponseFailed() {
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(),"请求失败");

        }
    }

    public static class MyHandler extends android.os.Handler{
        private OutingFragment mOuter;

        public MyHandler(OutingFragment mOuter) {
            this.mOuter = mOuter;
        }
        public void release(){
            new WeakReference<OutingFragment>(mOuter);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    IOrder.getInstance().getParts(mOuter.myGetPartsListener);
                    break;
                case 2:
                    mOuter.mPartSpinnerPopWindow.notifyDataSetChanged();
                    break;
            }
        }
    }




}
